//
//  HomeViewController.m
//  XRSquare
//
//  Created by UaenaMo on 2018/7/26.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "HomeViewController.h"
#import "BannnerTableViewCell.h"
#import "ContentTableViewCell.h"
#import "CityViewController.h"
#import "NotificationViewController.h"
#import "JobDetailViewController.h"
#import "HomeDetailViewController.h"
#import "SortViewController.h"
@import CoreLocation;
#define IOS8 [[[UIDevice currentDevice] systemVersion]floatValue]>=8.0

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate,contentSelectionDelegate,citySelectDelegate,BannerDelegate>
{
    UITableView * tableView;
    NSArray * banner;
    NSArray * content1;
    NSArray * content2;
    NSArray * content3;
    NSArray * content4;
    
    NSString * cityCurrent;
}
@property(nonatomic,retain)CLLocationManager *locationManager;

@end

@implementation HomeViewController

//开始定位
-(void)locationStart{
    //判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        //设置定位精度
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次（这里的设置为每隔百米)
        if (IOS8) {
            //使用应用程序期间允许访问位置数据
            [self.locationManager requestWhenInUseAuthorization];
        }
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        NSLog(@"%@",@"定位服务当前可能尚未打开，请设置打开！");
        
    }
}
#pragma mark - CoreLocation Delegate

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [self.locationManager stopUpdatingLocation];
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count >0)
         {
             
             [[NSUserDefaults
               standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans",
                                                nil] forKey:@"AppleLanguages"];
             
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市
             NSString *currCity = placemark.locality;
             if (!currCity) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 currCity = placemark.administrativeArea;
             }
             cityCurrent = currCity;
             [[NSUserDefaults standardUserDefaults]setObject:currCity forKey:@"city"];
             [[NSUserDefaults standardUserDefaults]setObject:currCity forKey:@"geocity"];

             
             [NetRequestCenter CITYset:currCity result:^(BOOL success, NSDictionary *resultDic) {
                 if (success) {
                     [self request];
                 }
             }];
             
             UIBarButtonItem * left = [[UIBarButtonItem alloc]initWithTitle:currCity style:UIBarButtonItemStylePlain target:self action:@selector(selectLocation)];
             self.navigationItem.leftBarButtonItem = left;
             
         } else if (error ==nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }else if (error !=nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
         
     }];
    
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (error.code ==kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
    
}

-(void)selectLocation
{
    self.tabBarController.tabBar.hidden = YES;

    CityViewController *cityPickerVC = [[CityViewController alloc] init];
    cityPickerVC.citySA = YES;
    cityPickerVC.delegate = self;
    cityPickerVC.showTop = YES;
    cityPickerVC.selectCity = cityCurrent;
    [self.navigationController pushViewController:cityPickerVC animated:YES];
}

-(void)city:(NSString *)city province:(NSString *)province code:(NSString *)code
{
    UIBarButtonItem * left = [[UIBarButtonItem alloc]initWithTitle:city style:UIBarButtonItemStylePlain target:self action:@selector(selectLocation)];
    self.navigationItem.leftBarButtonItem = left;
    cityCurrent = city;
    [[NSUserDefaults standardUserDefaults]setObject:cityCurrent forKey:@"city"];
    [NetRequestCenter CITYset:city result:^(BOOL success, NSDictionary *resultDic) {
        if (success) {
            [self request];
        }
    }];
}

//- (void) cityPickerController:(GYZChooseCityController *)chooseCityController didSelectCity:(GYZCity *)city
//{
//    UIBarButtonItem * left = [[UIBarButtonItem alloc]initWithTitle:city style:UIBarButtonItemStylePlain target:self action:@selector(selectLocation)];
//    self.navigationItem.leftBarButtonItem = left;
//
//    [chooseCityController dismissViewControllerAnimated:YES completion:nil];
//}
//
//- (void) cityPickerControllerDidCancel:(GYZChooseCityController *)chooseCityController
//{
//    [chooseCityController dismissViewControllerAnimated:YES completion:nil];
//}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];

    
    UIBarButtonItem * notification = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"android-notifications"] style:UIBarButtonItemStylePlain target:self action:@selector(notificationAction)];
    self.navigationItem.rightBarButtonItem = notification;
    UIBarButtonItem * left = [[UIBarButtonItem alloc]initWithTitle:@"选择城市" style:UIBarButtonItemStylePlain target:self action:@selector(selectLocation)];
    self.navigationItem.leftBarButtonItem = left;
    tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    
    [self locationStart];
    [self request];
}

-(void)notificationAction
{
    self.tabBarController.tabBar.hidden = YES;

    NotificationViewController * no = [[NotificationViewController alloc]init];
    [self.navigationController pushViewController:no animated:YES];
}

-(void)request
{
    [NetRequestCenter homeResult:^(BOOL success, NSDictionary *resultDic) {
        if (success) {
            NSLog(@"%@",resultDic);
            banner = [[resultDic objectForKey:@"data"]objectForKey:@"Banner"];
            content1 = [[resultDic objectForKey:@"data"]objectForKey:@"Activity"];
            content2 = [[resultDic objectForKey:@"data"]objectForKey:@"Job"];
            content3 = [[resultDic objectForKey:@"data"]objectForKey:@"Talent"];
            content4 = [[resultDic objectForKey:@"data"]objectForKey:@"Demand"];

            [tableView reloadData];
        }
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        return [BannnerTableViewCell height];
    }
    else
    {
        if (indexPath.row == 0)
        {
            return [ContentTableViewCell heightwithData:content1];
        }
        else if (indexPath.row == 1)
        {
            return [ContentTableViewCell heightwithData:content2];
        }
        else if (indexPath.row == 2)
        {
            return [ContentTableViewCell heightwithData:content3];
        }
        else
        {
            return [ContentTableViewCell heightwithData:content4];
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        static NSString * identifer = @"identifer";
        BannnerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[BannnerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
        cell.delegate = self;
        [cell loadData:banner];
        return cell;
    }
    else
    {
        static NSString * identifer = @"conten";
        ContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[ContentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
        cell.delegate = self;
        cell.indexPathCurrent = indexPath;
        cell.contentindexPath = indexPath;
        if (indexPath.row == 1)
        {
            [cell loadData:content1 title:@"公益活动 >"];
        }
        else if (indexPath.row == 2)
        {
            [cell loadData:content2 title:@"社会实践 >"];
        }
        else if (indexPath.row == 3)
        {
            [cell loadData:content3 title:@"技能售卖 >"];
        }
        else
        {
            [cell loadData:content4 title:@"需求发布 >"];
        }
        return cell;
    }
}

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(void)selectedContent:(NSDictionary *)content title:(NSIndexPath *)title
{
    self.tabBarController.tabBar.hidden = YES;

    if (title.row == 1)
    {
        HomeDetailViewController * job = [[HomeDetailViewController alloc]init];
        job.contentid = [content objectForKey:@"TaskID"];
        [self.navigationController pushViewController:job animated:YES];
    }
    else if (title.row == 2)
    {
        HomeDetailViewController * job = [[HomeDetailViewController alloc]init];
        job.contentid = [content objectForKey:@"TaskID"];
        [self.navigationController pushViewController:job animated:YES];
    }
    else if (title.row == 3)
    {
        JobDetailViewController * job = [[JobDetailViewController alloc]init];
        job.contentid = [content objectForKey:@"TaskID"];
        job.demand = NO;
        [self.navigationController pushViewController:job animated:YES];
    }
    else
    {
        JobDetailViewController * job = [[JobDetailViewController alloc]init];
        job.contentid = [content objectForKey:@"TaskID"];
        job.demand = YES;
        [self.navigationController pushViewController:job animated:YES];
    }
}

-(void)selectedBanner:(NSDictionary *)bannerDic
{
    WebViewController * web = [[WebViewController alloc]init];
    web.url = [bannerDic objectForKey:@"Target"];
    [self.navigationController pushViewController:web animated:YES];
    
    self.tabBarController.tabBar.hidden = YES;
}

-(void)selectContentIndex:(NSInteger)index
{
    if (index == 1)
    {
        self.tabBarController.selectedIndex = 1;
        UINavigationController * nav = [self.tabBarController.viewControllers objectAtIndex:1];
        [(SortViewController *)[nav.viewControllers firstObject] selection3];
    }
    else if (index == 2)
    {
        self.tabBarController.selectedIndex = 1;
        UINavigationController * nav = [self.tabBarController.viewControllers objectAtIndex:1];
        [(SortViewController *)[nav.viewControllers firstObject] selection4];
    }
    else if (index == 3)
    {
        self.tabBarController.selectedIndex = 1;
        UINavigationController * nav = [self.tabBarController.viewControllers objectAtIndex:1];
        [(SortViewController *)[nav.viewControllers firstObject] selection1];
    }
    else
    {
        self.tabBarController.selectedIndex = 1;
        UINavigationController * nav = [self.tabBarController.viewControllers objectAtIndex:1];
        [(SortViewController *)[nav.viewControllers firstObject] selection2];
    
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
